package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.如果不符合返回错误信息
            return Result.fail("手机号的格式有误!");
        }

        //3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);

        //4. 保存验证码到redis
//        session.setAttribute("code",code);
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5.发送验证码
        log.debug("产生的六位数字验证码为 ：{}", code);
        return Result.ok();
    }


    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        //1.校验手机号
        String phone = loginForm.getPhone();
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        //2.TODO 校验验证码(以手机号为KEY查找验证码)
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
//        Object code = session.getAttribute("code");
        if (code == null) {
            return Result.fail("请先点击按钮获取验证码");
        }
        if (phoneInvalid == true || !loginForm.getCode().equals(code)) {
            //3.不一致：报错
            return Result.fail("您输入的验证码有误");
        }
        //4.一致：根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //5.判断用户是否存在
        if (user == null) {
            //6.不存在 ，创建新用户并且保存到数据库中
            user = createUserWithPhone(phone);
        }
        //7. 保存信息到redis中（用随机的token作为KEY存储）
        //7.1生成token
        String token = UUID.randomUUID().toString();
        String tokenStr = LOGIN_USER_KEY + token;
        //7.2将用户信息保存到redis中
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        stringRedisTemplate.opsForHash().putAll(tokenStr,
                BeanUtil.beanToMap(userDTO, new HashMap<>(),
                        CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())));
        //7.3为用户信息设置保存时长
        stringRedisTemplate.expire(tokenStr, LOGIN_USER_TTL, TimeUnit.SECONDS);
//        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok(token);
    }


    /**
     * 实现用户签到功能
     */
    @Override
    public void sign() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();

        String KEY = USER_SIGN_KEY + userId + date;
        //利用用户信息和日期的值拼装key
        stringRedisTemplate.opsForValue().setBit(KEY, dayOfMonth - 1, true);
    }

    /**
     * 这个方法用来统计最近连续签到天数
     *
     * @return 连续签到的天数
     */
    @Override
    public Result signCount() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        int dayOfMonth = now.getDayOfMonth();
        String KEY = USER_SIGN_KEY + userId + date; // key get u14 0
        List<Long> list = stringRedisTemplate.opsForValue().bitField(KEY, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if (list == null || list.isEmpty()) {
            return Result.ok(0);
        }
        Long num = list.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        int count = 0;
        while (true) {
            if ((num & 1) == 0) {
                //未签到，跳出循环
                break;
            } else {
                //签到，计数器+1
                count++;
            }
            num >>>= 1;     //无符号右移
        }
        return Result.ok(count);
    }


    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomNumbers(20));
        save(user);
        return user;
    }
}
